//
//  OrderDetailController.m
//  zhijianshejian
//
//  Created by admin on 16/6/8.
//  Copyright © 2016年 haoniu-duhuan. All rights reserved.
//

#import "OrderDetailController.h"
#import "OrderProductListController.h"



@interface OrderDetailController ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray * _dataSource;
    NSMutableArray * _rowHeight;
    
    NSDictionary * _orderInfo;
    NSMutableDictionary * _address;
    NSMutableDictionary * _orderDic;
}


@property (nonatomic,strong) NSArray *goodsArr;
@property (nonatomic,strong) NSDictionary *addressDic;

@property (nonatomic,assign) BOOL isShow;

@end

@implementation OrderDetailController
- (IBAction)toPayPage:(id)sender {
    [self hideHud];
    if (_address==nil) {
        [self showHint:@"请选择收货地址"];
        return;
    }
       NSLog(@"_orderInfo = %@",_orderInfo);
    NSDictionary *orderDic = [_orderInfo objectForKey:@"order"];
    
    NSString * userId = [orderDic objectForKey:@"userId"];
     NSString * orderIds = [orderDic objectForKey:@"uuid"];
        NSString * addressId = [orderDic objectForKey:@"address"];
//    订单支付校验
    [self hideHud];
    [self showHudInView:self.view hint:@"订单校验..."];
    NSLog(@"orderIds = %@",orderIds);
//    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithObjectsAndKeys:tokenString,@"token", nil];
//    [param setObject:userId forKey:@"userId"];
//    [param setObject:orderIds forKey:@"orderIds"];
//    [param setObject:addressId forKey:@"addressId"];
//    NSLog(@"====param:%@",param);
//    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:_BaseURL]];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager POST:url_OrderPay parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSError * error;
//        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
//        NSLog(@"====data:%@",data);
//        [self hideHud];
//        if (error) {
//            NSLog(@"====error:%@",error);
//            [self showHint:@"订单校验失败"];
//            return;
//        }
//        NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
//        if ([code isEqualToString:@"0"]) {
//       
//                PayOrderController * payOrder = [[PayOrderController alloc]init];
//                [payOrder setOrderNo:_orderNo];
//                [payOrder setOrderPrice:[NSString stringWithFormat:@"%0.2f",[[_order objectForKey:@"payedMoney"] floatValue]]];
//                [payOrder setIsPersonal:@"1"];
//                [self.navigationController pushViewController:payOrder animated:YES];
//       
//
//        }else{
//            
//            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
//            [self showHint:info];
//            
//            NSLog(@"info = %@",info);
//            //去支付
//            //    [self hideHud];
//   
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
//        NSLog(@"====error:%@",error);
//        [self hideHud];
//        [self showHint:@"订单校验失败"];
//    }];
   }

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"订单详情";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
//    UIBarButtonItem * itemLeft = [[UIBarButtonItem alloc]init];
//    [itemLeft setImage:[UIImage imageNamed:@"fanhui"]];
//    [itemLeft setTarget:self];
//    [itemLeft setAction:@selector(backBtnClick)];
//    self.navigationItem.leftBarButtonItem=itemLeft;
    
    int buttonW = (mainScreenSize.width-90)/3-10+20;
    _dataSource = [NSMutableArray array];
    if ([_orderState isEqualToString: @"-1"] || [_orderState isEqualToString: @"-2"] ) {
        _rowHeight = [NSMutableArray arrayWithObjects:@"10",@"80",@"10",[NSString stringWithFormat:@"%d",buttonW],@"10",@"50",@"10",@"50",@"50",@"50",@"50",@"50", nil];
    }else{
          _rowHeight = [NSMutableArray arrayWithObjects:@"10",@"80",@"10",[NSString stringWithFormat:@"%d",buttonW],@"10",@"50",@"10",@"50",@"50",@"50",@"50", nil];
    }
    _tableView.dataSource =self;
    _tableView.delegate = self;
    [_tableView setBackgroundColor:[AppConfig colorWithHexString:@"f5f5f5"]];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    NSLog(@"====orderinfo:%@",_address);
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
    
    [self getOrderDetail];
}
-(void)backBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%ld",[_rowHeight count]);
    
    return [_rowHeight count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"--------%ld",indexPath.row);
    
    if (indexPath.row == 5) {
        return 0;
    }
    
    if (indexPath.row==1) {
//        if (_address==nil) {
//            return 50;
//        }else{
            return 80;
//        }
    }
    int h = [_rowHeight[indexPath.row] intValue];
    if (indexPath.row == 10) {
        NSLog(@"%d",h);
        return h;
    }
    if(indexPath.row==11){
        NSString *cancelReasonStr = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"orderMsg"]];
        
        NSLog(@"%@ ---- %@",cancelReasonStr,_orderDic);
        
        if (cancelReasonStr.length == 0 || [cancelReasonStr isEqualToString:@"(null)"]|| [cancelReasonStr isEqualToString:@"<null>"]|| [cancelReasonStr isEqualToString:@"null"])
        {
            h = 0;
            self.isShow = NO;
        }else{
            h = 50;
            self.isShow = YES;
        }
    }
    
    
    
    return h;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    int h = [_rowHeight[indexPath.row] intValue];
    UITableViewCell * cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"UITableViewCell"];
    [cell setFrame:CGRectMake(0, 0, mainScreenSize.width, h)];
    [cell.textLabel setTextColor:[AppConfig colorWithHexString:@"#454545"]];
    [cell.detailTextLabel setTextColor:[AppConfig colorWithHexString:@"#454545"]];
    if (h==10) {
        [cell setBackgroundColor:[AppConfig colorWithHexString:@"f5f5f5"]];
    }else if(indexPath.row==1){
//        if (_address && _address.count>0) {
            //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
//            cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_jt"]];
            [cell.accessoryView setHidden:NO];
            UIImageView * backImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"xiadanbj"]];
            [cell setBackgroundView:backImg];
        
        NSString *buyerNickname = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"buyerNickname"]];
        NSString *buyerUsername = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"buyerUsername"]];
        
            UILabel * leftTop = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, mainScreenSize.width/2-10, 30)];
        if ([AppConfig isNULL:buyerNickname]) {
            [leftTop setText:buyerUsername];
        }else{
            [leftTop setText:buyerNickname];
        }
        
            [leftTop setTextColor:[AppConfig colorWithHexString:@"#454545"]];
            [leftTop setFont:[UIFont systemFontOfSize:16]];
            [cell addSubview:leftTop];
            
            UILabel * rightTop = [[UILabel alloc]initWithFrame:CGRectMake(mainScreenSize.width/2, 5, mainScreenSize.width/2-30, 30)];
            [rightTop setText:buyerUsername];
            [rightTop setTextColor:[AppConfig colorWithHexString:@"#454545"]];
            [rightTop setFont:[UIFont systemFontOfSize:16]];
            [cell addSubview:rightTop];
            
            NSMutableString * addr = [NSMutableString string];
//            if ([_address objectForKey:@"provinceName"]!=nil) {
//                [addr appendString:[_address objectForKey:@"provinceName"]];
//            }
//            if ([_address objectForKey:@"cityName"]!=nil) {
//                [addr appendString:[_address objectForKey:@"cityName"]];
//            }
//            if ([_address objectForKey:@"areaName"]!=nil) {
//                [addr appendString:[_address objectForKey:@"areaName"]];
//            }
        
             NSString *addressName = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"addressName"]];
            if ([AppConfig isNULL:addressName]) {
                [addr appendString:@"未设置"];
            }else{
             [addr appendString:addressName];
            }
            
            UILabel * foot = [[UILabel alloc]initWithFrame:CGRectMake(10, 35, mainScreenSize.width-40, 45)];
            [foot setText:addr];
            [foot setTextColor:[AppConfig colorWithHexString:@"#454545"]];
            [foot setFont:[UIFont systemFontOfSize:16]];
            [foot setNumberOfLines:0];
            [cell addSubview:foot];
            //cell.textLabel.text = _address;
            cell.textLabel.textColor = [AppConfig colorWithHexString:@"#454545"];
//        }else{
//            [cell.imageView setImage:[UIImage imageNamed:@"jiahaoOrder"]];
//            cell.textLabel.text = @"添加收货地址";
//            cell.textLabel.textColor = [AppConfig colorWithHexString:@"#ff5341"];
//        }
    }else if(indexPath.row==5){
//        [cell.textLabel setText:@"支付方式"];
//        [cell.detailTextLabel setText:@"在线支付"];
    }else if(indexPath.row==7){
        [cell.textLabel setText:@"订单号"];
        [cell.detailTextLabel setText:[NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"orderSn"]]];
        UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(0, 49, mainScreenSize.width, 1)];
        [line setBackgroundColor:[AppConfig colorWithHexString:@"#f5f5f5"]];
        [cell addSubview:line];
    }else if(indexPath.row==8){
        [cell.textLabel setText:@"主治医生"];
        [cell.detailTextLabel setText:[NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"title"] ]];
        UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(0, 49, mainScreenSize.width, 1)];
        [line setBackgroundColor:[AppConfig colorWithHexString:@"#f5f5f5"]];
        [cell addSubview:line];
    }else if(indexPath.row==9){
        [cell.textLabel setText:@"总金额"];
        [cell.detailTextLabel setText:[NSString stringWithFormat:@"¥ %0.2f",[[_orderDic objectForKey:@"money"] floatValue]]];
        NSLog(@"--------_order = %@",_orderDic);
        
        UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(0, 49, mainScreenSize.width, 1)];
        [line setBackgroundColor:[AppConfig colorWithHexString:@"#f5f5f5"]];
        [cell addSubview:line];
    }else if(indexPath.row==11 && self.isShow){
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
                NSString *cancelReasonStr = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"orderMsg"]];
                
                NSLog(@"%@ ---- %@",cancelReasonStr,_orderDic);
                
                if (cancelReasonStr.length == 0 || [cancelReasonStr isEqualToString:@"(null)"]|| [cancelReasonStr isEqualToString:@"<null>"]|| [cancelReasonStr isEqualToString:@"null"]) {
                    [cell.textLabel setText:@""];
                    [cell.detailTextLabel setText:@""];
                }else{
                    [cell.textLabel setText:@"取消原因"];
                    NSLog(@"----cancelReasonStr = %@",cancelReasonStr );
                    cell.detailTextLabel.text  = cancelReasonStr;
                }
                
                UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(0, 49, mainScreenSize.width, 1)];
                [line setBackgroundColor:[AppConfig colorWithHexString:@"#f5f5f5"]];
                [cell addSubview:line];

            });
        });
        
    }else if(indexPath.row==10){
        [cell.textLabel setText:@"订单创建时间"];
        [cell.detailTextLabel setText:[NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"createTime"]]];
        NSLog(@"--------_order = %@",_orderDic);
        
        UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(0, 49, mainScreenSize.width, 1)];
        [line setBackgroundColor:[AppConfig colorWithHexString:@"#f5f5f5"]];
        [cell addSubview:line];
        
    }else if (indexPath.row==3){
        //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_jt"]];
        [cell.accessoryView setHidden:NO];
        
        int buttonW = (mainScreenSize.width-120)/3-10;
        NSArray * map = _goodsArr;
        for (int i=0; i<map.count; i++) {
            if (i<3) {
                NSDictionary * dict = map[i];
                UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10+(buttonW+10)*i, 10, buttonW, buttonW)];
                NSString * prodImg = [NSString stringWithFormat:@"%@%@",url_Base,[dict objectForKey:@"goodsImg"]];
                [imageView sd_setImageWithURL:[NSURL URLWithString:prodImg] placeholderImage:[UIImage imageNamed:@"shopping_image"]];
                [cell addSubview:imageView];
            }else{
                break;
            }
        }
        [cell.detailTextLabel setText:[NSString stringWithFormat:@"共%d种药",(int)map.count]];
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
    
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 1 && !_isOrderManager) {
//        AddressListController * addrs = [[AddressListController alloc]init];
//        addrs.delegate = self;
//        addrs.isDelegate = YES;
//        [self.navigationController pushViewController:addrs animated:YES];
    }else if (indexPath.row == 3) {
        OrderProductListController * proList = [[OrderProductListController alloc]init];
        [proList setDataSource:_goodsArr];
        [self.navigationController pushViewController:proList animated:YES];
    }
}
#pragma -mark AddressListControllerDelegate
-(void)AddressListControllerSelectItem:(NSDictionary *)dict{
    NSLog(@"====dict:%@",dict);
    _address = [NSMutableDictionary dictionaryWithDictionary:dict];
    NSIndexPath * indexpath = [NSIndexPath indexPathForRow:1 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexpath] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getOrderDetail{
    if (_orderSn==nil) {
        return;
    }

    [self hideHud];
    [self showHudInView:self.view hint:nil];
    NSMutableDictionary *param = nil;
    
    param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:_orderSn forKey:@"orderSn"];

    NSLog(@"param = %@",param);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_order_consult parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取医生详情失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSMutableArray * obj = [NSMutableArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",obj);
            
            _orderDic = [NSDictionary dictionaryWithDictionary:obj[0]];
            _goodsArr = [NSArray arrayWithArray:[_orderDic objectForKey:@"goods"]];
//            _addressDic = [NSDictionary dictionaryWithDictionary:[_orderDic objectForKey:@"goods"]];
            
            
            [self.tableView reloadData];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
            [self.tableView.mj_header endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取医生详情失败"];
        [self.tableView.mj_header endRefreshing];
        
    }];

}


@end
